package com.ossean.match.matchprocess;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.ossean.match.dao.ProjectDao;
import com.ossean.match.lucene.LuceneIndex;
import com.ossean.match.model.Project;

@Component("prjtomemomatch")
public class PrjToMemoMatch implements Runnable {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private int step = 10000; // 批量读项目数量
	private MatchIncrement matchIncrement = null;
	@Resource
	private ProjectDao projectDao;
	@Qualifier("match")
	@Autowired
	private Match match;

	public void setMatchIncrement(MatchIncrement matchIncrement) {
		this.matchIncrement = matchIncrement;
	}

	public void prjToMemoIncrement() throws IOException, SQLException {
		matchIncrement.setCurrentMatchDone(false);
		matchIncrement.getMatchRecord();
		// 批量读取filtration为1或者filtration为2且update_mark不为空的项目。即未匹配的和已匹配但有更新的。
		List<Project> newPrjs = projectDao.getBatchPrjsIncre(step);  
		while (newPrjs != null && newPrjs.size() > 0) {
			if (newPrjs != null) {
				match.prjToMemoMatch(newPrjs);
				// adding projects index
				LuceneIndex luceneIndex = new LuceneIndex();
				luceneIndex.prjIndexIncrement(newPrjs);
			}
			// getting projects' id and prjName in batches
			newPrjs = projectDao.getBatchPrjsIncre(step);
		}
		matchIncrement.setCurrentMatchDone(true);
	}
	
	public void run() {
		if (matchIncrement.isNewPrjComing()) {
			logger.info("start osps_to_relative_memos match!!!");
			try {
				prjToMemoIncrement();
			} catch (IOException e) {
				logger.error("IOException: " + e);
			} catch (SQLException e) {
				logger.error("SQLException: " + e);
			}
		}

	}

}
